package BLC

import (
	"github.com/boltdb/bolt"
	"log"
)

/**
	迭代器，首先要有好去一个迭代器，生成1个迭代器，在通过next不断迭代
 */
//迭代器
func (blockchain *BlockChain) Iterator() *BlockChainIterator  {
	return &BlockChainIterator{blockchain.Tip,blockchain.DB}
}

type BlockChainIterator struct {
	CurrentHash []byte  // 当前hash
	DB *bolt.DB
}

func (blockchainIterator *BlockChainIterator) Next() *Block  {

	var block *Block

	err := blockchainIterator.DB.View(func(tx *bolt.Tx) error {

		b := tx.Bucket([]byte(blockTableName))

		if b != nil {
			currentBlockBytes := b.Get(blockchainIterator.CurrentHash)
			// 反序列
			block = DeserializeBlock(currentBlockBytes)

			//更新迭起里面的CurrentHash
			blockchainIterator.CurrentHash = block.PrevBlockHash

		}

		return nil
	})

	if err != nil {
		log.Panic(err)
	}

	return block

}